package cays.img360;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONPath;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;

/**
 * 下载360图片
 *
 * @author Chai yansheng
 * @create 2019/8/17
 **/
public class Image360Demo {
    public static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
            "(KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.3636";

    /**
     * 将图片保存到本地文件夹
     * @param imageUrl
     */
    public void downloadImage(String imageUrl) {
        // 若指定文件夹没有，则先创建
        String filePath = "src\\main\\java\\cays\\img360\\img\\";
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 截取图片文件名
        String fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1, imageUrl.length());

        try {
            // 文件名里面可能有中文或者空格，所以这里要进行处理。但空格又会被URLEncoder转义为加号
            String urlTail = URLEncoder.encode(fileName, "UTF-8");
            // 因此要将加号转化为UTF-8格式的%20
            imageUrl = imageUrl.substring(0, imageUrl.lastIndexOf('/') + 1) + urlTail.replaceAll("\\+", "\\%20");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 写出的路径
        File file = new File(filePath + File.separator + fileName);

        try {
            // 获取图片URL
            URL url = new URL(imageUrl);
            // 获得连接
            URLConnection connection = url.openConnection();
            // 设置10秒的相应时间
            connection.setConnectTimeout(10 * 1000);
            // 获得输入流
            InputStream in = connection.getInputStream();
            // 获得输出流
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            // 构建缓冲区
            byte[] buf = new byte[1024];
            int size;
            // 写入到文件
            while (-1 != (size = in.read(buf))) {
                out.write(buf, 0, size);
            }
            out.close();
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Json数据体body
     * @param url json接口
     * @return
     */
    public String getResponseBody(String url) {
        String body = "";
        try {
            // Jsoup获取JSON页面数据失败 org.jsoup.UnsupportedMimeTypeException: Unhandled content type. Must be text/*, application/xml, or application/json
            // 调用 .ignoreContentType(true)
            Connection.Response response = Jsoup.connect(url)
                    .ignoreContentType(true)
                    .header("User-Agent",USER_AGENT)
                    .timeout(3000)
                    .execute();
            body = response.body();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }
    /**
     * 执行下载
     * @param url
     */
    public void execute(String url) {
        String body = getResponseBody(url);
        if (body.isEmpty()) {
            return;
        }
        // JSONPath读取图片地址
        List<String> imgUrls = (List<String>) JSONPath.read(body, "$.list[*].qhimg_url");
        // 下载图片
        imgUrls.forEach(imgUrl -> {
            System.out.println(imgUrl);
            downloadImage(imgUrl);
        });
    }
    public static void main(String[] args) {
        Image360Demo image360Demo = new Image360Demo();
        String ch = "beauty", t1 = "595", listtype = "hot", sn = "0";
        String url = "http://image.so.com/zjl?";
        url = url + "ch=" + ch + "&t1=" + t1 + "&listtype=" + listtype + "&sn=" + sn + "&temp=1";
        image360Demo.execute(url);
        /*for (int i = 0; i < 10; i++) {
            sn = String.valueOf(i * 30);
            url = url + "ch=" + ch + "&t1=" + t1 + "&listtype=" + listtype + "&sn=" + sn + "&temp=1";
            image360Demo.execute(url);
        }*/
    }
}
